//
//  LFTMCCountDownView.m
//  Pods
//
//  Created by Thomas Quan on 2017/5/14.
//
//

#import "LFTMCCountDownView.h"
#import "NTESGlobalMacro.h"

@interface LFTMCCountDownView()

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSTimeInterval totalTime;
@property (nonatomic, assign) NSTimeInterval elapsedTime;
@property (nonatomic, assign) NSTimeInterval fireInterval;

@property (nonatomic, strong) UILabel *counterLabel;
@property (nonatomic, assign) NSInteger currentCounterValue;

@property (nonatomic, strong) UIColor *givenLineColor;

@end


@implementation LFTMCCountDownView

- (void)setCounterValue:(NSInteger)newValue {
    if (self.currentCounterValue == newValue) {
        return;
    }
    
    self.currentCounterValue = newValue;
    
    if (!self.isLabelHidden) {
        if (self.finishingText && _currentCounterValue == 0) {
            _counterLabel.text = self.finishingText;
        } else {
            _counterLabel.text = [NSString stringWithFormat:@"%lds", _currentCounterValue];
            NSInteger lastDeadTime;
            if (self.deadTime) {
                lastDeadTime = self.deadTime;
            } else {
                lastDeadTime = (NSInteger)self.totalTime / 2;
            }
            if (_currentCounterValue <= lastDeadTime) {
                self.lineColor = [UIColor redColor];
                self.counterLabel.textColor = [UIColor redColor];
            } else {
                self.lineColor = UIColorFromRGB(0x97CC00);
                self.counterLabel.textColor = UIColorFromRGB(0x97CC00);
            }
        }
    }
    
    if ([self.delegate respondsToSelector:@selector(timerDidUpdateCounterValue:)]) {
        [self.delegate timerDidUpdateCounterValue:_currentCounterValue];
    }
}

#pragma Init

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        if (self.bgdColor) {
            self.backgroundColor = self.bgdColor;
        }
        
        self.layer.cornerRadius = self.frame.size.width / 2;
        self.clipsToBounds = YES;
        
        self.isLabelHidden = NO;
        
        self.totalTime = 0;
        self.elapsedTime = 0;
        self.fireInterval = 0.3f;
        
        _isPlaying = NO;
        _isEnded = YES;
        [self setupCounterLabel];
    }
    return self;
}

- (void)resetSelf {
    if (self.bgdColor) {
        self.backgroundColor = self.bgdColor;
    }
    
    self.isLabelHidden = NO;
    
    self.totalTime = 0;
    self.elapsedTime = 0;
    self.fireInterval = 0.2f;
    
    _isPlaying = NO;
    _isEnded = YES;
    [self setupCounterLabel];
}

- (void)setupCounterLabel {
    if (!_counterLabel) {
        _counterLabel = [[UILabel alloc] init];
        [self addSubview:_counterLabel];
    }
    
    _counterLabel.textAlignment = NSTextAlignmentCenter;
    _counterLabel.textColor = self.lineColor;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _counterLabel.frame = self.bounds;
    if (self.labelFont) {
        _counterLabel.font = self.labelFont;
    }
    if (self.lineColor) {
        _counterLabel.textColor = self.lineColor;
        self.givenLineColor = self.lineColor;
    }
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat radius = ( rect.size.width - self.lineWidth ) / 2;
    CGFloat currentAngle = (CGFloat)((M_PI * 2 * self.elapsedTime) / self.totalTime);
    
    CGContextSetLineWidth(context, self.lineWidth);
    
    CGContextBeginPath(context);
    CGContextAddArc(context,
                    CGRectGetMidX(rect),
                    CGRectGetMidY(rect),
                    radius,
                    - M_PI_2,
                    - M_PI_2 - currentAngle,
                    YES);
    CGContextSetStrokeColorWithColor(context, self.trailLineColor.CGColor);
    CGContextStrokePath(context);
    
    CGContextBeginPath(context);
    CGContextAddArc(context,
                    CGRectGetMidX(rect),
                    CGRectGetMidY(rect),
                    radius,
                    - M_PI_2 - currentAngle,
                    - M_PI_2,
                    YES);
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
    CGContextStrokePath(context);
}

- (void)correct:(NSTimeInterval)correctTime {
    
//    self.elapsedTime = correctTime;
//    NSLog(@"%@")
    
}

- (void)LFTMCTimer {
    self.elapsedTime += self.fireInterval;
    
    if (self.elapsedTime < self.totalTime) {
        [self setNeedsDisplay];
        
        NSInteger computedCountValue = (NSInteger)(self.totalTime - self.elapsedTime);
        if (computedCountValue != self.currentCounterValue) {
            [self setCounterValue:computedCountValue];
        }
    } else {
        [self setCounterValue:0];
        [self resetSelf];
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)start:(NSInteger)beginingValue interval:(NSTimeInterval)interval {
    self.totalTime = (NSTimeInterval)beginingValue * interval;
    self.elapsedTime = 0;
    [self setCounterValue:beginingValue];
    
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer timerWithTimeInterval:self.fireInterval
                                         target:self
                                       selector:@selector(LFTMCTimer)
                                       userInfo:nil
                                        repeats:YES];
    
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    _isPlaying = YES;
    _isEnded = NO;
    
    if ([self.delegate respondsToSelector:@selector(timerDidstart)]) {
        [self.delegate timerDidstart];
    }
}

//- (void)start:(NSInteger)beginingValue interval:(NSTimeInterval)interval {
//
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//    
//    dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,10*NSEC_PER_MSEC, 0); //每秒执行
//    
//    self.totalTime = (NSTimeInterval)beginingValue * interval;
//    if (self.elapsedTime > 0.f) {
//        dispatch_source_cancel(timer);
//    }
//    self.elapsedTime = 0.f;
//    [self setCounterValue:beginingValue];
//
//    dispatch_source_set_event_handler(timer, ^{
//        
//        if(self.elapsedTime >= self.totalTime) {
//            dispatch_source_cancel(timer);
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self setNeedsDisplay];
//                [self setCounterValue:0];
//                [self resetSelf];
//            });
//        } else {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self setNeedsDisplay];
//                NSInteger computedCountValue = beginingValue - self.elapsedTime;
//                if (computedCountValue != self.currentCounterValue) {
//                    [self setCounterValue:computedCountValue];
//                }
//            });
//            
//            self.elapsedTime += self.fireInterval;
//        }
//    });
//    
//    dispatch_resume(timer);
//    
//    if ([self.delegate respondsToSelector:@selector(timerDidstart)]) {
//        [self.delegate timerDidstart];
//    }
//}

//- (void)pause {
//    self.timer.fireDate = [NSDate distantFuture];
//    
//    _isPlaying = NO;
//    _isEnded = NO;
//    
//    if ([self.delegate respondsToSelector:@selector(timerDidPause)]) {
//        [self.delegate timerDidPause];
//    }
//}
//
//
//- (void)resume {
//    self.timer.fireDate = [[NSDate alloc] init];
//    
//    _isPlaying = YES;
//    _isEnded = NO;
//    
//    if ([self.delegate respondsToSelector:@selector(timerDidResume)]) {
//        [self.delegate timerDidResume];
//    }
//}




@end

